import 'package:flutter/material.dart';
import 'package:intl/intl.dart'; // 日期格式化库

class DateInputField extends StatefulWidget {
  final ValueChanged<String> onValueSelected;
  final String label;
  const DateInputField({
    super.key,
    required this.onValueSelected,
    required this.label,
  });

  @override
  _DateInputFieldState createState() => _DateInputFieldState();
}

class _DateInputFieldState extends State<DateInputField> {
  final TextEditingController _dateController = TextEditingController();
  DateTime? _selectedDate;

  Future<void> _selectDate() async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: _selectedDate ?? DateTime.now(),
      firstDate: DateTime(2000),
      lastDate: DateTime(2100),
    );
    if (picked != null && picked != _selectedDate) {
      setState(() {
        _selectedDate = picked;
        _dateController.text = DateFormat('yyyy-MM-dd').format(picked); // 格式化日期
        widget.onValueSelected(_dateController.text);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return TextFormField(
      controller: _dateController,
      decoration: InputDecoration(
        labelText: '${widget.label}',
        prefixIcon: Icon(Icons.calendar_today),
        border: OutlineInputBorder(),
      ),
      readOnly: true, // 禁止手动输入
      onTap: _selectDate, // 点击触发日期选择
    );
  }
}
